//
//  YZMThreeQutoesViewController.m
//  YZMicroStock
//
//  Created by apple on 2017/11/28.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMThreeQutoesViewController.h"
#import "YZMThreeQutoesCell.h"
#import "YZGeneralResultModel.h"
#import "YZClient+Quote.h"
#import "YZMTrendPacket.h"
#import "YZMTrendItem.h"
#import "YZMStockRealModel.h"
#import "NSNumber+Utils.h"
#import "NavigationTitleView.h"
#import "YZMTradeFilterView.h"
#import "YZMPullListView.h"
#import "YZMAppDelegate.h"
#import "YZMThreeQutoesLandScapeCell.h"

static NSString *const identifier = @"YZMThreeQutoesCell";

static NSString *const identifier_LandScape = @"YZMThreeQutoesLandScapeCell";

@interface YZMThreeQutoesViewController ()<UITableViewDataSource,UITableViewDelegate,NavigationTitleViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (nonatomic, strong) NSString *stockCode;

@property (nonatomic, strong) NSString *stockName;

@property (nonatomic, strong) YZMStockRealModel *stockReal;

@property (nonatomic, strong) YZMTrendPacket *trendPacket;

@property (nonatomic, strong) NSTimer *trendTimer;

@property (nonatomic, assign) BOOL unShowErrorFlag;

@property (nonatomic, assign) BOOL unFirstFetchFlag;

@property (nonatomic, strong) NavigationTitleView *navTitleView;

@property (nonatomic, strong) YZMPullListView *filterView;

@property (nonatomic, strong) NSArray *totalArray;

@property (nonatomic, strong) NSMutableArray *pullArrayData;


@property (nonatomic, assign) BOOL switchCode;

@property (nonatomic, strong) YZMThreeQutoesLandScapeCell *landscapeCell;


@end

@implementation YZMThreeQutoesViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        _trendPacket = [[YZMTrendPacket alloc] init];
        _pullArrayData = [NSMutableArray array];
        _totalArray = @[@{@"code":@"SH000001",@"name":@"上证指数"},@{@"code":@"SZ399001",@"name":@"深证成指"},@{@"code":@"SZ399006",@"name":@"创业板指"}];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configView];
    [self startTimer];
}

- (void)configView{
    self.navigationItem.titleView = self.navTitleView;
    self.navTitleView.title =  self.stockName;
    self.view.backgroundColor = [YZMAppStyle colorForMain];
    _myTableView.backgroundColor = [YZMAppStyle colorForMain];
    [_myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YZMThreeQutoesCell class]) bundle:nil] forCellReuseIdentifier:identifier];
    [_myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YZMThreeQutoesLandScapeCell class]) bundle:nil] forCellReuseIdentifier:identifier_LandScape];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTableView.estimatedRowHeight = 0;
}


- (void)startTimer{
    if (self.trendTimer == nil) {
        self.trendTimer = [NSTimer timerWithTimeInterval: 1.0 target:self selector: @selector(dataUpdateTimer:) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.trendTimer forMode: NSRunLoopCommonModes];
        [self.trendTimer fire];
    }
}

- (void)stopTimer{
    [self.trendTimer invalidate];
    self.trendTimer = nil;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self.myTableView reloadData];
    switch (toInterfaceOrientation) {
        case UIInterfaceOrientationLandscapeRight:
        case UIInterfaceOrientationLandscapeLeft:
            self.navigationController.navigationBar.hidden = YES;
            break;
        case UIDeviceOrientationPortrait:
            self.navigationController.navigationBar.hidden = NO;
            break;
            
        default:
            break;
    }
    
}

//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}
//
////设置是否隐藏
//- (BOOL)prefersStatusBarHidden {
//    [super prefersStatusBarHidden];
//    return NO;
//}
//
////设置隐藏动画
//- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
//    return UIStatusBarAnimationNone;
//}


+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMThreeQutoesViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams:(NSDictionary *)params{
    self.stockCode = params[@"code"];
    self.stockName = params[@"name"];
    for (NSDictionary *dic in self.totalArray) {
        if (![dic[@"code"] isEqualToString:self.stockCode]) {
            [self.pullArrayData addObject:dic];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
    if (appDelegate.allowRotation) {
        YZMThreeQutoesLandScapeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier_LandScape forIndexPath:indexPath];
        cell.realInfo = self.stockReal;
        cell.trendPacket = self.trendPacket;
        self.landscapeCell = cell;
        return cell;
    }
    YZMThreeQutoesCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.realInfo = self.stockReal;
    cell.trendPacket = self.trendPacket;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
    if (appDelegate.allowRotation) {
        return ScreenHeight - 64;
    }
    return 455;
}

- (void)dataUpdateTimer: (NSTimer *)timer
{
    if (kNetworkNotReachability) {
        if (!self.unShowErrorFlag) {
            [MBProgressHUD showMessage:@"网络无法连接，无法获取行情信息"];
            self.unShowErrorFlag = YES;
        }
        return;
    }
    
    [self requestToLoadReal];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self stopTimer];
    if (self.landscapeCell) {
        [self.landscapeCell stopTimer];
    }
}



#pragma mark - netWork

//- (void)refreshData{
//    if (![self.trendPacket lastItem]) {
//        [self requestToLoadTrend];
//    }
//}

- (void)requestToLoadReal{
    
    __weak typeof(&*self) safeSelf = self;
    [YZClient qt_getRealtimeInfoWithStockCodes:@[self.stockCode] success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            NSDictionary *dict = topModel.data;
            if (!safeSelf.stockReal) {
                safeSelf.stockReal = dict[safeSelf.stockCode];
            }
            safeSelf.stockReal = dict[safeSelf.stockCode];
//            safeSelf.infoView.realStock = dict[self.stockCode];
            if ( [@(safeSelf.stockReal.price) isEqualGreaterThanDouble:0.0] ) {
                YZMStockRealModel *realInfo =   dict[safeSelf.stockCode];
                safeSelf.trendPacket.closePrice  = realInfo.lastClosePrice;
                safeSelf.trendPacket.highPrice = realInfo.highPrice;
                safeSelf.trendPacket.lowPrice = realInfo.lowPrice;
                [self requestToLoadTrend];
//                [safeSelf.quoteView updateRealInfo:dict[self.stockCode]];
//                [safeSelf.quoteView refreshData];
            }
        }else{
            [safeSelf stopTimer];
            [topModel showMessage];
        }
        self.unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        if (!self.unShowErrorFlag) {
            [error yz_showMessage];
        }
    }];
}

- (void)requestToLoadTrend
{
    __weak typeof(&*self) safeSelf = self;
    NSString *beginTimeStr = nil;
    if (!self.switchCode) {
        YZMTrendItem *lastItem = [self.trendPacket lastItem];
        if (lastItem) {
            beginTimeStr = [NSString stringWithFormat: @"%lld", lastItem.time];
        }
    }
    WS(ws);
    [YZClient qt_getTrendInfoWithStockCode: self.stockCode andBegin: beginTimeStr success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *result = responseObject;
        
        if (result.success) {
            YZMTrendItem *newItem = [result.data lastObject];
            if (![newItem.code isEqualToString: safeSelf.stockCode]) {
                return ;
            }
            if (!ws.switchCode) {
                YZMTrendItem *currentLast = [safeSelf.trendPacket lastItem];
                if (currentLast) {
                    [safeSelf.trendPacket updateFromItems: result.data];
                }else
                {
                    [safeSelf.trendPacket setOriginItems: result.data];
                }
            }else{
                [safeSelf.trendPacket setOriginItems: result.data];
                ws.switchCode = NO;
            }
            
//            [safeSelf.trendView updateFromDataPacket: safeSelf.trendPacket];
            [safeSelf.myTableView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@:%@", error.localizedDescription, error.localizedFailureReason);
        [error yz_showMessage];
    }];
}

#pragma mark - getter

- (NavigationTitleView *)navTitleView{
    if (!_navTitleView) {
        _navTitleView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([NavigationTitleView class]) owner:self options:nil][0];
        _navTitleView.delegate = self;
    }
    return _navTitleView;
}

- (YZMPullListView *)filterView{
    if (!_filterView) {
        _filterView = [[YZMPullListView alloc] initWithParentView:self.view relativeView:self.navigationController.navigationBar arrayData:_pullArrayData];
    }
    WS(ws);
    _filterView.handle = ^(NSDictionary *dic) {
        [ws.navTitleView showDown];
        ws.navTitleView.title = dic[@"name"];
        ws.stockName = dic[@"name"];
        ws.stockCode = dic[@"code"];
        [ws.pullArrayData removeAllObjects];
        for (NSDictionary *dict in ws.totalArray) {
            if (![dict[@"code"] isEqualToString:ws.stockCode]) {
                [ws.pullArrayData addObject:dict];
            }
        }
        ws.filterView.arrData = ws.pullArrayData;
        ws.switchCode = YES;
        [ws.myTableView reloadData];
        [ws requestToLoadReal];
    };
    
    _filterView.hiddenHandle = ^{
        [ws.navTitleView showDown];
    };
    return _filterView;
}

#pragma mark - NavigationTitleViewDelegate

- (void)pullListWith:(PullListType)type{
    switch (type) {
        case PullListTypeDown:
            [self.filterView show];
            break;
        case PullListTypeUp:
            [self.filterView hiddenSelf];
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
